package com.zmovie.front.controller;

import com.alibaba.fastjson.JSON;
import com.zmovie.framework.domain.*;
import com.zmovie.framework.service.*;
import com.zmovie.front.constant.Constants;
import com.zmovie.front.controller.vo.OrderVO;
import com.zmovie.front.controller.vo.SessionVO;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.yaml.snakeyaml.scanner.Constant;

import javax.servlet.http.HttpSession;
import java.util.List;
import java.util.stream.Collectors;

/**
 * @author 挚爱之夕
 * @version 1.0
 * @implSpec com.zmovie.front.controller
 * @since 2023-12-24 9:43
 */
@Controller
@RequestMapping("/user/space")
public class UserSpaceController {
    @Autowired
    private OrderService orderService;
    @Autowired
    private SessionService sessionService;
    @Autowired
    private HallService hallService;
    @Autowired
    private CinemaService cinemaService;
    @Autowired
    private MovieService movieService;
    @GetMapping
    public String index(Model model, HttpSession httpSession){
        User user = (User) httpSession.getAttribute(Constants.SESSION_USER_KEY);
        List<Order> orders = orderService.listOrderByUserId(user.getId());
        model.addAttribute(Constants.ORDER_LIST_KEY, convert(orders));
        return "user/user-space";
    }
    private List<OrderVO> convert(List<Order> orders){
        return orders.stream().map(this::convert).collect(Collectors.toList());
    }
    private OrderVO convert(Order order){
        OrderVO orderVO = new OrderVO();
        BeanUtils.copyProperties(order, orderVO);
        //场次
        Session session = sessionService.getById(order.getSessionId());
        orderVO.setSessionVO(convert(session));
        //座位
        List<int[]> seats = JSON.parseArray(order.getSeat(), int[].class);
        orderVO.setSeats(seats);
        return orderVO;
    }
    private SessionVO convert(Session session){
        SessionVO sessionVO = new SessionVO();
        BeanUtils.copyProperties(session, sessionVO);
        //电影
        Movie movie = movieService.getById(session.getMovieId());
        sessionVO.setMovie(movie);
        //影院
        Cinema cinema = cinemaService.getById(session.getCinemaId());
        sessionVO.setCinema(cinema);
        //影厅
        Hall hall = hallService.getById(session.getHallId());
        sessionVO.setHall(hall);
        return sessionVO;
    }
}
